<!--
* @Description: 创建一个Dropdown组件
* @Author: Rulyc
* @Operating:
-->
<template>
  <span class="lc-dropdown" ref="dropdownRef">
    <span class="lc-dropdown-title" @click.prevent="toggleOpen">
      <lc-button type="text"  v-if="title">{{ title }}</lc-button>
      <slot v-else name="title" ></slot>
    </span>
    <ul class="lc-dropdown-menu" v-if="isOpen">
      <slot></slot>
    </ul>
  </span>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import useClickOutside from '../hooks/useClickOutside'
export default defineComponent({
  name: 'LcDropdown',
  props: {
    title: { // title属性值
      type: String,
      required: false
    }
  },
  setup() {
    const dropdownRef = ref<null | HTMLElement>(null)
    const isOpen = ref(false)
    /** 点击事件 */
    const toggleOpen = ()=>{
      isOpen.value = !isOpen.value
    }
    // 引用公共的方法
    const isClickOutside = useClickOutside(dropdownRef)
    /** watch监听值的边话 */
    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside.value) {
        isOpen.value = false
      }
    })
    return {
      toggleOpen, isOpen, dropdownRef
    }
  }
})
</script>

<style lang="scss">
.lc-dropdown {
  position: relative;
  .lc-dropdown-menu {
    display: block;
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    padding: 10px 0px;
    min-width: 10rem;
    margin: 20px 0 0;
    font-size: 1rem;
    color: #212529;
    text-align: left;
    list-style: none;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid rgba(0,0,0,.15);
    border-radius: .25rem;
  }
}
</style>
